﻿using UnityEngine;
using System.Collections;

public class SpineShaderController : MonoBehaviour {

	private MeshRenderer meshRender;
	private Material[] materials = null;
	private Color[] colors;
	private float totalTime;
	private float time = 0.0f;
	private bool isFading = false;

	// Use this for initialization
	void Start () {
		//StartFade (1.0f);
	}
	
	// Update is called once per frame
	void LateUpdate () {
		if (isFading) {
			//Debug.LogWarning ("update SpineShaderController");
			materials = meshRender.materials;
			time += Time.deltaTime;
			float alpha;
			if (time < totalTime) {
				alpha = (time / totalTime) * 1.0f;
				alpha = 1.0f - alpha;
			} else {
				alpha = 0.0f;
				isFading = false;
			}
			//Debug.Log ("alpha is " + alpha);
			for (int i = 0; i < materials.Length; ++i) {
				colors [i] = materials [i].color; 
				colors [i].a = alpha;
				//Debug.Log ("color i " + i + "  " + colors [i]);
				materials [i].color = colors [i];
			}
		}
	}

	public void StartFade(float fadeTime) {
		//Debug.LogWarning ("fadetime " + fadeTime);
		meshRender = GetComponent<MeshRenderer> ();
		/*
		materials = new Material[meshRender.materials.Length];
		for (int i = 0; i < meshRender.materials.Length; ++i) {
			materials[i] = new Material()
		}
		*/
		//meshRender.sharedMaterial.color = Color.red;
		//meshRender.sharedMaterial = new Material (meshRender.sharedMaterial.shader);
		//meshRender.sharedMaterial.color = Color.red;

	
		materials = meshRender.materials;
		//new Material(meshRender.sharedMaterial.shader)
		colors = new Color[50];
		for (int i = 0; i < materials.Length; ++i) {
			//materials [i].color = Color.red;
			colors [i] = materials [i].color;
		}
		totalTime = fadeTime;
		time = 0.0f;
		isFading = true;
	
	}
}
